package income

import (
	"week13/log"
	"week13/errors"
	"week13/internal/data"
	"week13/pkg/constant"
)

type SettleRepository interface {
	SettleIncome(incomes []IncomeDo) error
}
type SettleDao struct {
}
//结算收入
func (s SettleDao) SettleIncome(incomes []IncomeDo) error  {
	db,err := data.DBEngin()
	if err != nil {
		return errors.NewConnectFail()
	}
	session := db.NewSession()
	session.Close()
	for _,income := range incomes {
		session.Begin()
		log.Info("settle Income Id:%d",income.Id)
		_, err = session.Exec("update income set state = ? where id=? and state = ?",constant.INCOME_STATE_SETTLE,income.Id,constant.INCOME_STATE_INIT)
		if err != nil {
			log.Warn("settle Income Id:%d fail",income.Id)
			session.Rollback()
			continue
		}
		_, err = session.Exec("update agent set balance = balance+? where agentid=?",income.Amount,income.AgentId)
		if err != nil {
			log.Error("settle Income Id:%d fail",income.Id)
			session.Rollback()
			continue
		}
		log.Info("settle Income Id:%d success",income.Id)
		session.Commit()
	}
	return nil
}
